<template>
    <a-modal v-model:visible="visible" title="文件上传" :width="600" @cancel="resetState">
        <a-upload :custom-request="customUpload" :show-file-list="false"
            accept=".doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,.xls,.xlsx,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            @before-upload="beforeUpload" @success="handleSuccess" @error="handleError">
            <template #upload-button>
                <a-space direction="vertical" size="large">
                    <a-typography-text type="secondary">
                        支持扩展名：.doc/.docx/.xls/.xlsx
                    </a-typography-text>
                    <a-button type="primary" :loading="uploading">
                        选择文件
                        <template #icon><icon-upload /></template>
                    </a-button>
                </a-space>
            </template>
        </a-upload>
    </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { Message } from '@arco-design/web-vue'
import { addKnowledge } from '@/apis/knowledge/knowledge'

const visible = ref(false);
const uploading = ref(false);
const selectedFilePath = ref("");
const selectedParentFolderId = ref("")
const emit = defineEmits(['save-success'])


const beforeUpload = (file: File) => {
    const validTypes = [
        'application/msword',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'application/vnd.ms-excel',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    ]
    const validExtensions = ['.doc', '.docx', '.xls', '.xlsx']

    const isValid = validTypes.includes(file.type) ||
        validExtensions.some(ext => file.name.toLowerCase().endsWith(ext))

    if (!isValid) {
        Message.error(`不支持的文件类型: ${file.name}，请上传Word或Excel文件`)
        return false
    }

    if (file.size > 10 * 1024 * 1024) { // 10MB限制
        Message.error(`文件大小超过限制: ${(file.size / 1024 / 1024).toFixed(1)}MB`)
        return false
    }

    return true
}

const customUpload = (options) => {
    const { fileItem, onProgress, onSuccess, onError } = options;
    const controller = new AbortController();

    // 构建 FormData（根据后端要求）
    const formData = new FormData();
    formData.append('files', fileItem.file);
    formData.append("physicalPath", selectedFilePath.value)
    formData.append('parentFolderId', selectedParentFolderId.value)
    formData.append('createUser', '1'); // 示例附加参数

    // 执行上传
    addKnowledge(formData).then(response => {
        // 标准化响应处理
        if (response.success) {
            onSuccess({
                ...fileItem,
                url: response.data.filePath, // 根据实际响应字段调整
                name: fileItem.name
            });
            return response;
        }
        throw new Error(response.message || '上传失败');
    }).catch(error => {
        onError({
            ...fileItem,
            error: error.message
        });
        throw error;
    });

    // 监听上传进度（需要后端支持进度返回）
    // 如果后端不支持进度，可删除这部分
    uploading.value = true;
    (progressEvent) => {
        const percent = Math.round(
            (progressEvent.loaded * 100) / progressEvent.total
        );
        onProgress(percent, progressEvent);
    };

    // 返回控制方法
    return {
        abort: () => {
            controller.abort();
            uploading.value = false;
            Message.warning('上传已取消');
        }
    };
};

// 事件处理
const handleSuccess = (fileItem) => {
    uploading.value = false;
    Message.success(`上传成功: ${fileItem.name}`);
    emit('save-success');
};

const handleError = (fileItem) => {
    uploading.value = false;
    Message.error(`上传失败: ${fileItem.error || '未知错误'}`);
};

// 状态重置
const resetState = () => {
    uploading.value = false;
    // fileList.value = []
    // Object.keys(uploadStatus).forEach(key => delete uploadStatus[key])
}

// 暴露打开方法
const open = (filePath: string, parentFolderId: string) => {
    visible.value = true
    selectedFilePath.value = filePath;
    selectedParentFolderId.value = parentFolderId
}


defineExpose({ open })
</script>

<style scoped>
.upload-wrapper {
    padding: 20px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;

    :deep(.arco-upload-list) {
        margin-top: 16px;
    }
}

.file-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 8px;
    border-bottom: 1px solid #f0f0f0;

    span:first-child {
        flex: 2;
    }

    span:nth-child(2) {
        flex: 1;
        text-align: right;
        color: #8c8c8c;
    }
}
</style>
